package com.hjf.ditubiaozhu.base;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;

import com.flyco.tablayout.SlidingTabLayout;

import com.hjf.ditubiaozhu.R;

/**
 * Created by hejianfeng on 17/1/31.
 */


public abstract class BaseViewPagerFragment extends BaseFragment {


    protected ViewPager mBaseViewPager;
    protected SlidingTabLayout mSlidingTabLayout;


    @Override
    public int getLayoutResId() {
        return R.layout.common_pager;
    }

    @Override
    protected void onCompletedView(Bundle savedInstanceState) {
        mBaseViewPager = findById(R.id.common_viewpager);
        mSlidingTabLayout=findById(R.id.sliding_tabs);
        BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(getFragmentManager(), getPagers());
        mBaseViewPager.setAdapter(adapter);
        mBaseViewPager.setCurrentItem(0, true);
        mSlidingTabLayout.setViewPager(mBaseViewPager);
    }

    /**
     * 只要重写这个就可以获取配置了
     * @return
     */
    protected abstract PagerInfo[] getPagers();

    /**
     * fragment的bean
     */
    public static class PagerInfo {
        private String title;
        private Class<?> clx;
        private Bundle args;

        public PagerInfo(String title, Class<?> clx, Bundle args) {
            this.title = title;
            this.clx = clx;
            this.args = args;
        }
    }


    /**
     * FragmentPagerAdapter基类
     * 传入 PagerInfo 以确定fragment和标题参数
     */
    public class BaseViewPagerAdapter extends FragmentPagerAdapter {
        private PagerInfo[] mInfoList;
        private Fragment mCurFragment;

        public BaseViewPagerAdapter(FragmentManager fm, PagerInfo[] infoList) {
            super(fm);
            mInfoList = infoList;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
            if (object instanceof Fragment) {
                mCurFragment = (Fragment) object;
            }
        }

        public Fragment getCurFragment() {
            return mCurFragment;
        }

        @Override
        public Fragment getItem(int position) {
            PagerInfo info = mInfoList[position];
            return Fragment.instantiate(getActivity(), info.clx.getName(), info.args);
        }

        @Override
        public int getCount() {
            return mInfoList.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mInfoList[position].title;
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }
}
